Angular Form Validation

I am stuck with certain scenarios in a validation. I need to valiadte a field - "First Name". Validations logic i have been using is -

  • If the field is dirty then validate against regex

ng-show="aspnetForm.FirstName.$dirty && aspnetForm.FirstName.$error.nameValidate"

  • If the field is marked required (currently keeping the field required is entirely business dependent so i am reading the true/false value from a JSON) then user may try submitting the form as it is

    ng-show="blankSubmit && aspnetForm.FirstName.$error.required"

where blankSubmit is just a scope variable i am setting true on submit button click.

  • Now 3rd scenario is the logic i am not getting that is if the user clicks on the firstname text box and then without dirtying it, just blurs out, then the validation message should be displayed if ng-required is set true.If i just place ng-show="aspnetForm.FirstName.$error.required" then on the page load itself the error message is displayed which i dont want as it gives user a bad UX.

    I solely want error message to be displayed when the attribute ng-required is set true and user blurs out of the textbox.

Answers


One possible solution is to create a directive which marks a field as visited which you can then check in the ng-show:

.directive('visited', function() {
    return{
        restrict: 'A',
        require: 'ngModel',
            link: function(scope, element, attrs, ngModel){
                element.bind('blur', function(){
                    scope.$apply(function() {
                        ngModel.visited = true;
                    });
            });
        }
    };
});

View:

ng-show='form.field.$error.required && (form.field.$dirty || form.field.visited)'

I would suggest you using ng-messages. Your HTML would look like this:

<div ng-messages="aspnetForm.FirstName.$error" role="alert">
    <div ng-message="required">Please enter a value for this field.</div>
    <div ng-message="nameValidate">This field must be a valid.</div>
    ...
</div>

In case you want to use required depending on some variables I would suggest you using this <input ... required={{shouldBeRequired}}/>. This should work, required field should be validated only when proper value is set to it.


Need Your Help

Good practice to pass variables between cucumber-jvm steps

java cucumber cucumber-jvm

To pass variables between steps now I'm doing something like the example as follows:

Issue with locĪ±ting HTML with Selenium

python selenium selenium-webdriver

Trying to learn Selenium for Python (3.4.0) and have had success with the basic things - installing, opening browser and web page, so on. But when I try to open a specific HTML form I am met with an