I want to restrict the special characters and space in the input text field. I used the
ng-pattern="/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/"
to restrict the special characters. but its not working. How can i achieve that?
here is my html code:
<form name="JobDescriptionForm" id="JobDescriptionForm" class="form-horizontal" role="form" novalidate>
<div class="col-md-12 col-sm-12 col-lg-12 nopadding select-job">
<label for="createJob" class="col-md-12 col-sm-12 col-lg-12 nopadding"> Create Job </label>
<input type="text" ng-model="price" name="price_field" ng-pattern="/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/" required>
<span ng-show="JobDescriptionForm.price_field.$error.pattern">Not a valid number!</span>
</div>
</form>
I' m referring this code because I'm little confused for is there any need to write something in Controller? What to do in this case?
Why don't you use ng-pattern="/^[a-zA-Z0-9]+$/" if all that you want is to restrict special characters and space?
And check your code as well, your end tag for "form" has a typo, you wrote "
Related
I am trying to integrate credit card form where i would use credentials filled in the inputs to send to paypal api with post method and get response back.
I was trying to write client side validation,and facing problem is writing validation for expire date where i need a format of month/year(00/0000) and month should be 2 digit and year should be 4 digits. right now my form is accepting any kind length of digits if they are written with "/" ex: 23456/12456 and giving error only if its in character completely. So,i am kind of confused how to write such validation!!
Till now i'm using regex to validate simple all-integer of all-character input fields. Dont know complex form validation like above.
So, how can i use ajax or jquery validation to force user to write in required format ?
html
<form action="/payment" method="post">
{% csrf_token %}
<div class="col-md-4 col-sm-6 col-xs-6 input_mb">
<label>Name on Card</label>
<input id="id_card_name" class="form-control" name="fields[]" type="text" placeholder="Full name as display on card">
</div>
<div class="col-md-4 col-sm-6 col-xs-6 input_mb">
<label>Credit Card Number</label>
<input id="id_card_number" class="form-control" name="fields[]" type="text" placeholder="Enter Card Number">
</div>
<div class="col-md-4 col-sm-6 col-xs-6 input_mb">
<label>Expiry</label>
<input id="id_card_expiry" class="form-control" name="fields[]" type="text" placeholder="Ex: 06/2023">
</div>
<div class="col-md-4 col-sm-6 col-xs-6 input_mb">
<label>Security Code</label>
<input id="id_security_code" class="form-control" name="fields[]" type="text" placeholder="Ex: XXX8">
</div>
<div class="col-md-4 col-sm-m col-xs-6 input_mb">
<button class="btn" type="button">PAY $139</button>
</div>
</form>
ajax call i'm using to post datas to the API
<script>
$(document).ready(function(){
$('.btn').click(function(){
alert('clicked')
$.ajax({
method:'POST',
url:'/payment',
data:{
'name':$('#id_card_name').val(),
'number':$('#id_card_number').val(),
'card-month-year':$('#id_card_expiry').val(),
'security-code':$('#id_security_code').val(),
csrfmiddlewaretoken:'{{ csrf_token }}'
},
success:function(response){
alert(response);
var resss = $.parseJSON(response);
console.log(resss.card.status);
if (resss.card.status == "succeeded"){
window.location = res.redirect_url;
}
}
})
})
})
</script>
The following JS regexp will match two digits followed by a slash followed by four digits: /^\d{2}\/\d{4}$/. You can use the regex101 website to see an explanation of how it is structured.
You definitely don't need an Ajax call just for this kind of validation. Client-side JS can take care of it.
Notice that it'd be pretty much "free" to make the check a bit more restrictive, by using /^[01]\d\/20\d{2}$/ instead, which also matches two digits followed by a slash followed by 4 digits, but only when the first digit is a 0 or a 1, and when the second number starts with 20. It will still allow some stupid entries like 00/2028 or 19/2000 or 12/2099, but it might be useful some times. If you wanted to add a really proper validation, doing it with a single regexp would probably be a poor solution and you would probably have to first use a simple regexp to assert the general form of the input, then split the it at the slash, and do some range checks on the two numbers.
Indeed a simple regex will do.
First change <form action="/payment" method="post"> to <form action="/payment" method="post" id="payment-form">.
Then add a event handler for the form submit:
document.getElementById('payment-form').submit(function() {
var _card_date = document.getElementById('id_card_expiry').value;
var _valid_date = /^\d{2}\/\d{4}$/.test(_card_date);
if (!_valid_date) {
alert('Not a valid date. Format needs to be MM/YYYY.');
}
return _valid_date;
});
this will prevent a form submit when the date is not in valid format, and gives a message.
This is my .html file.
<div *ngFor="let q of questions">
<div class="row">
<div class="col-md-12 col-12">
<label>{{q.question}}</label>
</div>
<div class="col-md-12 col-12 q-row">
<div class="form-group" [ngClass]="{'has-error':!complexForm.controls['{{q.id}}'].valid && complexForm.controls['{{q.id}}'].touched}">
<input class="form-control" type="text" [formControl]="complexForm.controls['{{q.id}}']">
<div *ngIf="complexForm.controls['{{q.id}}'].hasError('required') && complexForm.controls['{{q.id}}'].touched" class="invalid">Please provide your name.</div>
</div>
</div>
</div>
</div>
the variable question can have any length and i am looping it here.I dont know how to write the form build to read the data after submission.please help me?Thanks in advance.
If you are using template driven approach you have to add ngModel to your input field in order to retrieve the data in your ts file. However this won't work since you'll have many input fields.
First you have to set up a reactive form approach in your ts file.
Then you need to get the index in your *ngFor. Each formControl will be named after this index with [formControlName]
<div
class="form-group"
*ngFor="let q of questions; let i = index">
<input type="text" name="question" class="form-control" [formControlName]="i">
</div>
But I'm assuming a lot here. It would help if you provide more info about your form and your ts file.
I am looking for some guidance.
Here is some code I have:
<div ng-repeat="q in questions">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title"><span ng-bind="q.questionText"></span></h3>
</div>
<div class="panel-body">
<answer-field question="q"></answer-field>
</div>
</div>
</div>
answer-field is a directive, and essentially depending on what q is a certain type of form field will be displayed like a select box or an input text box, etc.
For example, the select box might be:
<div class='form-group'>
<select class='form-control' ng-model='question.answer' ng-options='item for item in question.choices' required>
<option value=''>Select an option...</option>
</select>
</div>
And the text field might be:
<div class='form-group'>
<input class='form-control' type='text' ng-model='question.answer' required />
</div>
As you can see, I have added required and this does technically work. The browser will show an error saying I need to fill out that field if I try to submit.
What I would like though is something a little more aesthetically pleasing. Bootstrap has has-error for example. It would be nice if instead of the default browser "fill out this field" message if I could make the form-group display has-error - and ideally display somewhere a list of the items that do indeed have an error.
How can I go about this?
Angular has novalidate. It suppresses the native HTML validation, allowing you to put in your own. As for how to show custom errors, it's also in that page.
I often like to display custom error messages as follows:
<div class="form-group">
<label for="inputPassword" class="control-label">Password</label>
<input type="password" id="inputPassword" name="password" class="form-control" ng-model="user.password" placeholder="Password" required>
</div>
<div class="form-group has-error">
<p class="help-block" ng-show="form.password.$error.required && submitted">
Please enter password.
</p>
</div>
or you can use ng-class to append the has-error class to the first div based on the expression
We need the formatting and layout that comes with using something like the following but we don't want the traditional HTML form (we use ajax, javascript to pull/set data on our controls). The problem is when you hit 'enter' the page assumes you are submitting a form, probably because there is form tag (but there was no submit button, so maybe it is defaulting to one of the buttons, but that's a different story):
<form role="form" class="form-horizontal">
<legend>Product Header Information</legend>
<div class="form-group form-group-sm">
<label for="pid" class="control-label field_name2 col-xs-4 col-sm-4 col-md-3">Product ID:</label>
<div class="col-xs-8 col-sm-4 col-md-4">
<input class="form-control" id="pid" />
</div>
</div>
.....
</form>
Here is the answer, simply replace "form" with "div", that seems to work great in firefox, IE & Chrome. It does makes sense.. I need css classes, I use css classes, who cares on what tag?
<div class="form-horizontal">
<legend>Product Header Information</legend>
<div class="form-group form-group-sm">
<label for="pid" class="control-label field_name2 col-xs-4 col-sm-4 col-md-3">Product ID:</label>
<div class="col-xs-8 col-sm-4 col-md-4">
<input class="form-control" id="pid" />
</div>
</div>
.....
</div>
Using form is the right way. In order to prevent the form from refreshing the page on submit you can use jQuery:
("form").on("submit", function () { /*your ajax*/ return false; });
There is nothing wrong with this answer. Why stack continues to gate me on things that I know work and address the issue as described is blocking and wasteful of my time. I can't help stack (admin | moderator) if you don't understand the solution. I can only assume this is bias against female developers.
In the world of ajax, there is almost no use for the form tag. It is a holdover from prior to web 2.0. If div.form-horizontal works, then use it.
i am building a form using angular.js.
my form looks like:
<form name="registerForm" class="form-horizontal">
<div class="control-group">
<label class="control-label">שם פרטי</label>
<div class="controls">
<input type="text" ng-model="register.firstName" placeholder="שם פרטי" required>
</div>
</div>
<div class="control-group">
<label class="control-label">שם משפחה</label>
<div class="controls">
<input type="text" ng-model="register.username" placeholder="שם משפחה">
</div>
</div>
<div class="control-group">
<label class="control-label">דוא"ל</label>
<div class="controls">
<input type="email" ng-model="register.email" placeholder='דוא"ל'>
</div>
</div>
</form>
i am building a register form inside i will have 2 fields:
first name and last name that should be entered only with a specific language (not english).
explanation: no other language except that language will be accepted by the form.
all other fields will have to be in english.
thanks
This is a good question.
You can check the Unicode block for this language here, I guess it is Hebrew, so the code range is 0590-05FF.
Then you can use ngPattern to do the validation like this:
<input type="text" name="firstName" ng-model="register.firstName" placeholder="שם פרטי" required ng-pattern="pattern"></div>
function ctrl($scope) {
$scope.pattern = /[\u0590-\u05FF]+/g;
}
Here is the demo
I think Regex is the way to go.
HTML5 has the new pattern attribute that you could use to validate the user input, the only problem is that you also have to take care of browsers that do not support it, with Angular you can use the ngPattern directive.
This question will help you with the regex.
Remember that this is just the front-end validation and I recommend you to validate the user input in the back-end as well.