JavaScript - how to validate field to allow certain character and certain length - javascript

I need to validate a textbox, so it's value consist of 10 characters (not more, not less). The below code does it, allowing me to set the restricted length for each field separately.
function charLength(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
alert("Invalid number of characters");
elem.focus();
return false;
}else{
return true;
}
}
and this is how I'm calling it:
onBlur="charLength(document.getElementById('tf1'),1,9)"
but the field that I validate must not only be 10 characters long, but it also has to start with letter Z.
How would I do such validation? is it possible in the first place?

try it also:
function charZ10(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max && uInput.substr(0, 1) == "Z"){
alert("Material number has to consist of 10 characters begining with Z");
elem.focus();
return false;
}
else return true; //i
}
and try to add maxlength in the textbox
<input type="text" maxlength="10">

function charZ10(elem, min, max){
var uInput = elem.value;
if(uInput.length == 10 && uInput.substr(0, 1) == "Z")
return true;
alert("Material number has to consist of 10 characters begining with Z");
elem.focus();
return false;
}

function charZ10(elem) {
var pass = /^Z.{9}$/.test(elem.value); // 10 chars starting with Z
if (!pass) {
alert("Try again, noob.");
elem.focus();
}
return pass;
}

Must be
if(uInput.length <= 10 && substr(uInput,0, 1) == "Z")

Related

If/Else Statement

Hi what am I doing wrong with this if statement? Ive tried making the second one and else if and the last one an else as well but cant get the alerts to respond properly.
prompt("Please enter a number");
if(x < 100) {
alert("variable is less 100")
}
if(x == 100) {
alert("variable is equal to 100!")
}
if(x > 100) {
alert("variable was greater than 100")
}
thanks!
You are missing an assignment to variable x.
var x = prompt("Please enter a number");
//^^^^^
Then you could use parseInt to get a integer number from the string
x = parseInt(x, 10);

How do I change the format of digit inputs

Basically, I want to change a person input from 0######### to (0#)########, the event im using is onblur
function numberChange(){
var check = document.getElementById("number").value;
var regCheck = /^[0-9]+$/;
if (check != 10 || !regCheck)
{
alert("Please input your 10 digit mobile number")
return false;
}
else if (check == 10 || regCheck)
{
return true;
}
}
Your regCheck should be ^\(0\d\)\d{8}$
Demo
Update :
This regex validates the number of characters, you can omit length check in your code :
function numberChange(){
var check = document.getElementById("number").value;
var re = new RegExp(/^\(0\d\)\d{8}$/);
if (re.test(check)) {
return true;
}
else {
alert("Please input your 10 digit mobile number")
return false;
}
}
This will check for 10 digits, first number is zero, and that all inputs are digits. Once all of that passes the code will add the '(' & ')' to it. This approach gives specific errors depending on how the user incorrectly entered the number.
<html>
<body>
Phone number: <input type="text" id="number" onblur="checkNumber()">
<script>
function checkNumber() {
var x = document.getElementById("number").value;
// Check for 10 digits.
if(x.length != 10) {
alert('The number must be 10 digits.');
return false;
}
// Make sure the first digit is 0.
if(x.charAt(0) != 0) {
alert('The first digit must be 0.');
return false;
}
// Make sure all digits are numbers and not characters.
if(isNaN(x) == true) {
alert('All digits must be numbers.');
return false;
}
// If here then everything else passed so add the '(' and ')' to the number.
document.getElementById("number").value = '(0' + x.charAt(1) + ')' + x.substring(2, 10);
}
</script>
</body>
</html>

Control sum from input boxes in javascript

I'm trying to make some controls in Javascript when I submit a form in HTML.
Evertyhing works perfectly except the one that needs to check the sum of 2 fields.
<script type="text/javascript">
function validation()
{
var count=0;
if((document.getElementsByName("people")[0].selectedIndex) == "")
{alert("How many PEOPLE?"); count++;}
else if((document.getElementsByName("amount")[0].selectedIndex) == "")
{alert("AMOUNT has to be at least 1."); count++;}
else if((document.getElementsByName("deposit")[0].value) == "")
{alert("DEPOSIT cannot be empty."); count++;}
else if((document.getElementsByName("deposit")[0].value) < "20")
{alert("DEPOSIT must be at least 20."); count++;}
else if((document.getElementsByName("topay")[0].value) == "")
{alert("Mark 0 in TO PAY if they dont have to pay more."); count++;}
else if( ( (document.getElementsByName("deposit")[0].value) + (document.getElementsByName("topay")[0].value) ) < "40")
{alert("The minimum price of this product is 40"); count++;}
else if((document.getElementsByName("seller")[0].value) == "")
{alert("Who is the SELLER?"); count++;}
else if(isNaN(document.getElementsByName("topay")[0].value))
{alert("TO PAY must be a number"); count++;}
else if(isNaN(document.getElementsByName("people")[0].value))
{alert("PEOPLE must be a number"); count++;}
else if(isNaN(document.getElementsByName("deposit")[0].value))
{alert("DEPOSIT must be a number"); count++;}
else if(isNaN(document.getElementsByName("amount")[0].value))
{alert("AMOUNT must be a number"); count++;}
return (count==0);
}
</script>
The one that I'm not able to solve is:
else if( (((document.getElementsByName("deposit")[0].value) + (document.getElementsByName("topay")[0].value)) < "40)")
{alert("The minimum price of this product is 40"); count++;}
I want it to check if (deposit + topay) < 40. I noticed that with this code it is just checking if (deposit < 40) and I don't understand why.
Can you please help me?
The '+' operator acts as concatenation operator in a conditional statement(or generally performs concatenation).
Hence to make it perform addition operation use,
else if( ((parseInt(document.getElementsByName("deposit")[0].value) + parseInt(document.getElementsByName("topay")[0].value)) < 40))
{alert("The minimum price of this product is 40"); count++;}
var abc = parseInt(
(document.getElementsByName("deposit")[0].value)+(document.getElementsByName("topay")[0].value)
) if( abc < "40" ) { alert("h"+abc); }
change your if condition to this
if( (((document.getElementsByName("deposit")[0].value) + (document.getElementsByName("topay")[0].value)) < 40))

How to get alerts for inputed name length of characters - javascript

Hello im trying to do a simple script here when i enter name in input field, i want to get certain alerts for example:
- if name is > 20 characters alert = "name is bigger than 20"
- if name is between 12 and 20 alert = exact number of chars of the name that was inputed
- if name is bigger than 2 chars and bigger or equal than 20 = alert that name
this was just an example of what im trying to do, but im just noob at this point im only 1 month into javascript(html and css) so if anyone can point me in the right direction i would appreciate.
Ok, so far i have this:
<form name="myForm" id="form2" onsubmit="return validate()">
Input name: <input type="text" name = "myName" id="t" />
<input type="submit" name="submit" value="submit" />
</form>
function validate() {
if(document.myForm.myName.value.length>20){
alert("your name is too big");
submitFlag=false; // im not sure what this line does //
} else if(document.myForm.myName.value.length=12-20){
alert("your name is" + document.myForm.myName.value.length + " chars");
} else if(document.myForm.myName.value.length=0){
alert("input name")
}else{
alert("ok e")
}
return submitFlag;
}
THe if statements are workin only if i have two, im getting only the first 2 alerts, so i would like to input more else if statements and to get alerts for them also, i tried to put some more myself, but the dont work, im only getting the first two.
Extending what #dfsq have said,.. you try to get:
if name is between 12 and 20
that means smth like:
document.myForm.myName.value.length > 12 && document.myForm.myName.value.length <= 20
And make your code more simple and readable. And don't forget to return false (your submitFlag):
function validate() {
var len = document.myForm.myName.value.length;
if (len > 20)
{
alert("your name is too big");
}
else if (len > 12 && len <= 20)
{
alert("your name is" + len + " chars");
}
else if (len == 0)
{
alert("input name");
}
else
{
//in fact it would alert when name between 0 and 12
alert("ok e");
}
return false;
}
There are a difference between operators. = is an assignment, == and === are comparison operators. You need latter:
document.myForm.myName.value.length == 0
Here we go:
function validate() {
var charLength = document.myForm.myName.value.length,
submitFlag = false; // This flag would be used further to stop the use going ahead from this particular validation
if (charLength > 20) {
// length more than 20
alert("your name is too big");
} else if (charLength <= 20 && charLength > 12) {
// length between 20 and 12
alert("your name is" + charLength + " chars");
} else if (charLength == 0) {
// If no input there
alert("enter name");
} else {
// Otherwise in success condition
alert("ok e");
submitFlag = true;
}
return submitFlag;
}
Jsfiddle: http://jsfiddle.net/fcwbkkd7/

Checking for alphabet and numeric chars in a field

I am trying to write javascript code for making sure a field in my form has its first 2 characters as alphabets (US) and the rest 8 are numerics.
The total has to be 10, and if any of these are not satisfied, I should throw up an alert box.
I am checking for numerics now but I don't know how to combine checking for alphabets and numerics in the same field.
Here is my code for checking for numerics.
Please help me out! sid is my field name.
// only allow numbers to be entered
var checkOK = "0123456789";
var checkStr = document.forms[0].sid.value;
var allValid = true;
var allNum = "";
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
if (ch != ",")
allNum += ch;
}
if (!allValid)
{
alert("Please enter only 8 numeric characters in the \"sid\" field.");
return (false);
}
}
A single regular expression will easily perform this check :
/^[a-zA-Z]{2}\d{8}$/
/^ match beginning of string
[a-zA-Z]{2} match exactly 2 alphabetic characters
\d{8} match exactly 8 digits
$/ match end of string
Use as follows :
/^[a-zA-Z]{2}\d{8}$/.test (str) // Returns true or false
You can use regexp. jsfiddle
var regExp = /[a-z]{2}[0-9]{8}/i;
var text = 'ab12345678';
if(text .replace(/[a-z]{2}[0-9]{8}/i, "").length > 0){
alert("Please enter only 8 numeric characters in the \"sid\" field.");
return (false);
}
Simple regular expression, checks for 2 characters + 8 digits
var checkStr = document.forms[0].sid.value;
if (checkStr.match(/\b[A-z]{2}[0-9]{8}\b/) === null) {
alert("Please enter only 8 numeric characters in the \"sid\" field.");
return (false);
}
/^([a-zA-Z]{2}\d{8})$/; should check for 2 characters and then 8 decimals.

Categories

Resources