Jagadeesh
Jagadeesh

Reputation: 754

Date validation using ng-pattern is working, but also its get submitted when its in error

In my form I used ng-pattern for date, when i entered the wrong pattern and submit the form, its get submitted. Here my code.

<form role="form" name="editForm" ng-submit="saveRecord()">
    <label class="control-label">DATE</label>
    <input type="text" ng-model="userRecord.date" ng-pattern='/^((0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)[0-9]{2})*$/'
           name="date" class="form-control" required/>
           <div role="alert">
               <span style="color:red" ng-show="editForm.date.$dirty">
                   <span ng-show="editForm.date.$error.pattern">Incorrect Format, should be MM/DD/YYYY</span>
                   <span ng-show="editForm.date.$error.required">date is required.</span>
               </span>
           </div>
     <button type="submit" class="btn btn-primary" >Save</button> 
</form>

It will display the error also, but if i submit the form its get submited. I have tried with several searches but could not find solution for this.

Upvotes: 1

Views: 537

Answers (3)

Soni Kumari
Soni Kumari

Reputation: 116

Below is the code to stop submitting page if pattern does not match

<span class="error" style="color:red" ng-show="externalLinkForm.link.$error.pattern">
                                Please use hash</span>

To study detail about the validation rule needed in ng-pattern please see the link to get in detail of the validation rules

https://www.w3schools.com/Jsref/jsref_obj_regexp.asp

Upvotes: 0

Mark Veenstra
Mark Veenstra

Reputation: 4739

You can go down 2 paths:

  1. Disable the form button as long as the form is invalid
  2. You need to check in your form submit function if the form is valid or not

Solution 1

<button type="submit" class="btn btn-primary" ng-disabled="editForm.$invalid">Save</button> 

Solution 2

<form role="form" name="editForm" ng-submit="saveRecord(editForm.$valid)">

And now in your controller do the next in the saveRecord function:

$scope.saveRecord = function(valid) {
   if(!valid) { return; }
}

Upvotes: 1

Bhavesh Chauhan
Bhavesh Chauhan

Reputation: 1053

I think you have missed novalidate directory in form tag

like

<form role="form" name="editForm" ng-submit="saveRecord()" novalidate>

and edit also validate with submit button like

 ng-show="editForm.$submitted && editForm.date.$error.pattern"
 ng-show="editForm.$submitted && editForm.date.$error.required"

i hope its help

Upvotes: 0

Related Questions