0

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.

2 Answers 2

1

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)'
Sign up to request clarification or add additional context in comments.

2 Comments

I am actually new to angular. So if thats the best practise i will take that but is there no way other than creating a directive to do so
Not that I know of. You have a form which contains invalid fields and only want to show an error message once the field has been visited. I don't believe that angular provides a mechanism for handling such a scenario (nice if it did!).
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.