How to validate my form in JS? - javascript

I'm trying to validate the full name part of my form, the requirements are:
Only alphabet, spaces between words and "-" are valid.
Minimum of 3 characters and max of 35.
My HTML code is as follows:
function test(myForm)
{
var regex = /^[a-zA-Z]+$/;
if(regex.test(myForm.full_name.value) == false) {
alert("Name must be in alphabets only");
myForm.full_name.focus();
return false;
}
}
<tr>
<td>
<b>Full Name: </b>
</td>
<td>
<input type="text" name="full_name" placeholder="Full Name" required/>
</td>
</tr>

Try this regex, which doesn’t allow space or - characters at the start or end of the string:
var regex = /^[a-zA-Z][a-zA-Z- ]{1,33}[a-zA-Z]$/

This regex should do the work for you /(^[a-zA-Z -]{3,35}$)/
Explanation:
[a-zA-z -] -- Any character space or -
{3,35} -- repeat between 3 to 35 times
Example:
function test(name) {
var regex = /(^[a-zA-Z -]{3,35}$)/
return regex.test(name)
}
console.log(test('valid-name'))
console.log(test('valid Name'))
console.log(test('valid'))
console.log(test('in'))
console.log(test('invalid~name'))
console.log(test('invalidname invalidname invalidname invalidname'))

Related

How i can add comma after each entered number only

How can i add comma automatically after each entered number.
For example like : 1,2,3,4
If i add number 5 after 4 so it should be separated with the comma.
Below is my code.
function addComma(txt) {
txt.value = txt.value.replace(",", "").replace(/(\d+)(\d{3})/, "$1,$2");
}
<input type="text" id="txt" onkeyup="addComma(this);" />
the comma is separating after a few numbers. I require an auto-add comma after each number has been entered.
I change your RegEx. See below example.
function addComma(txt) {
txt.value = txt.value.replace(/(\d)(?=(\d)+(?!\d))/g, "$1,");
}
<input type="text" id="txt" onkeyup="addComma(this);" />

How to check for special characters when validating a form

I'm trying to add form validation into my form. I've managed to do it for character length, numbers, letters and all of them work fine, but it doesn't seem to work for special characters, such as # & * etc.
I've tried following an example from a previous question which created a variable for all the different special characters, and then I did here what I did with my other checks, matched the field input to the variable with the special characters to see if there are any, but it is not detecting them.
This is my JavaScript for this:
function ValidateActInsert() {
var specialChars = /[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z and 0-9 are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
And this is the HTML form that I am trying to do this on:
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
The code itself makes sense to me and i'd imagine that it would work and I honestly have no idea as to why it isn't
You were catching every symbol.
Let's just simple only allow
a-z lowercase,
A-Z uppercase and or
0-9 as #SterlingArcher said.
/[^a-zA-Z ]/g Will allow only a-z and A-Z
/[^a-zA-Z0-9 ]/g Will allow only a-z, A-Z, and 0-9
Letters and Numbers:
function ValidateActInsert() {
var specialChars = /[^a-zA-Z0-9 ]/g;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z and 0-9 are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
Numbers only
function ValidateActInsert() {
var specialChars = /[^a-zA-Z ]/g;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
I suggest using https://regexr.com/ to test expressions and to learn from some examples.
Use regex.test(val)
^[0-9a-zA-Z ]*$
^ start
[0-9a-zA-Z] only allow the characters inside [ ]
$ end * as many characters as it contains
function ValidateActInsert() {
var regex = /^[0-9a-zA-Z ]*$/;
var val = document.getElementsByTagName('input')[0].value;
if(!regex.test(val)){
alert("false");
}else{
alert("true");
}
return false;
}
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert">
<br>
<input type = "submit" value = "Insert">
</form>

<input type=“text” maxlength=“4”> should not count comma and dot in maxlength

I have input field which contains number and special characters e.g. comma and dot
while calulating the maxLength of the field i want to skip special characters .
I dont want to restrict the special character.
Expected Output should be :- 1,234 (Total Length :- 4)
<form action="/action_page.php">
Username: <input type="text" maxlength="3" id="myId"/>
<input type="submit" value="Submit">
</form>
jsfiddle link here
Try adding this javascript:
window.onload = function() {
var textInput = document.getElementById("myId");
textInput.oninput = function() {
var temp;
temp = this.value.replace(/[^\w\s]/gi,'');
if (temp.length > 3) {
alert("Invalid"); // Or other stuff you want to do
}
};
};
Note that this code checks input on real time
This should be done with javascript:
var input = document.getElementById('myId');
input.addEventListener('keyup', function () {
// Checking length of string ignoring all non-digit and non-letter characters
if (this.value.replace(/[^\d|[^a-zA-Z]]*/g, '').length == 3) {
console.log('stop and do whatever you need')
}
})
You can try to use HTML5 pattern attribute. Just instead of maxlength type pattern and give it some regex. Could do something like this:
<form action="/action_page.php">
Username: <input type="text" pattern="(?(?=^.\d{1,3},\d{1,3}$)^.{5}$|^.{4}$)" id="myId"/>
<input type="submit" value="Submit">
</form>

Check if the entire String value in Textbox is zero(0) or of special characters

I have a Textbox in which i'm getting the input of type text having the length 20, I have a scenario in which i have to evaluate whether the entire string input from the client is not zero or any special characters
e.g: 00000000000,00000,00,00000,00000/-/--,/-/-----////,aBadf-018---///sdf484,AA///---000
all these above inputs are invalid, the string could be of any length in between 2 to 20,
i have restricted the user to input other special characters other than hyphen and dash,
regex used over here to invalidate the value other than hyphen and dash are as follows :
" /[^a-zA-Z0-9/-]/g "
<input type="text" name="consumer_number" maxlength="25" ng-disabled="!form_data[selectedTab].electrici‌​ty.check" alpha-numeric-with-slash-and-hyphen data-ng-model="form_data[selectedTab].electric‌​ity.unique_no" class="input-field" data-ng-blur="validateElecConsumer(selectedTab‌​)" ng-class="{true:'invalid-field',false:''}[form‌​_data[selectedTab].e‌​lectricity.check && form_data[selectedTab].invalid.electricity]" required />
Now my concern is how could i display a message right upfront that whatever the input the user have provided is invalid.
This may help:
var app = angular.module("app", []);
app.controller("MyController", function($scope){
$scope.inputtext = "";
$scope.onSubmit = function() {
var val = $scope.inputtext;
if (val.length < 2
|| val.length > 20
|| !val.match(/[^a-zA-Z0-9/-]/g)) {
alert("Unacceptable");
} else {
alert("you pass");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyController">
<input maxlength="20"
id="inputtext"
ng-model="inputtext" type="text"/>
<button id="submitbutton" ng-click="onSubmit()" type="text">submit</button>
</div>

Validating Contact Number in javascript

I am having a textbox and a div in my form like this :
<input type="text" name="NContact" placeholder="New Contact No." id="txtNewContact"/>
<div id="divCheckContact">
Now on every key press of a key in NContact I need to check if the value entered is a number or not and also it is 10 digit number.And display message in the divison
How to do it Please help.
You can add a pattern and title to do this:
<input type="text" pattern="\d{10}" title="Type 10 digits please" />
The above will check for 10 digit number and if it isn't valid the title will be displayed.
Demo
Note: This is part of html5 spec. Will not work for IE 9 and below.
You can also do it in pure js:
var elem = document.getElementById('txtNewContact');
elem.onkeydown = function(){
if(!/\d{10}/.test(elem.value)){
alert("Type 10 digits please");
}
}
use this
Example
$('#txtNewContact').keyup(function(){
var re = isNaN($(this).val());
if(!re)
{
$('#divCheckContact').html("");
}else
{
$('#divCheckContact').html("please enter only numbers");
$(this).val('');
}
if($(this).val().length>10)
{
$('#divCheckContact').html("please enter only ten 10 digits contact no");
return false;
}
});

Categories

Resources