Referencing the length of a HTML number form element? - javascript

I have a form that takes numbers, and there is a specific (Phone number, or phNo) form element that I want to only accept 7 digits in length (no more, no less). Using Javascript the Idea is:
If element length not equal to 7: true else false
Here is my code:
var phNo = document.getElementsByName('phNo'); //here I try to get
the form value in the form of an object. This is where I think I am going wrong
var phNoString = phNo.toString(); //Not to sure if I need this line or not, read somewhere that .length only works on a string
if(phNoString.length != 7) {
//Do something for false
return;
} else {
//Do something for true
}
<form id="myForm" action="form_action.asp">
First name: <input type="text" name="fName"><br>
Last name: <input type="text" name="lName"><br>
Phone Number: <input type="number" name="phNo" max="7"><br>
Credit Card Number: <input type="number" name="cardNo"><br>
</form>
<input id="submit" type="button"value="Submit"onClick="detailsSubmit()">

var phNoString = phNo.toString();
This line will return [object HTMLInputElement], you need to use phNo.value if you want the value the user typed inside the input.
Not really related to the problem, but <input type="number" name="phNo" max="7"> here the max attribute only means the highest number possible in that input is 7. Using a browser that supports html5 inputs it's giving me an invalid highlight if I try to enter any phone number.
I would change it to a simple text field and use the maxlength attribute, which is probably what you intended;
<input type="text" name="phNo" maxlength="7">

"getElementsByName" returns a collection type, you should be doing like this to read the value from the element.
var phNoString = document.getElementsByName('phNo')[0].value;
if(phNoString.toString().length != 7) {
//Do something for false
return;
} else {
//Do something for true
}

If you did decide to leave it as a number input, you don't need to convert it to a string. Phone Numbers can't start with 0, so the smallest number would be 1000000. If your input has a max of 7, then you can check that the value is greater than that.
var phNoString = document.getElementsByName('phNo')[0].value;
if(var phNoString > 1000000){
// truthy
}else{
// falsey
}

The document.getElementsByName() function is depreciated in HTML5. See note in w3school site. Use document.getElementById() instead and add an ID tag to your phone input control.
Also use input type="tel" for your phone numbers. That way the browsers, especially on mobile devices, know how to correctly display the inputted value on the screen.
Finally, note the use of regular expressions to do a validation check on the inputted phone number. Also, it is important to note, the HTML5 regex validation runs after the JavaScript function executes. Below is a code snippet that you can sink your new developer teeth into:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
Phone Number (format: xxx-xxx-xxxx):: <input type="tel" id="phNo" name="phNo" pattern="^\d{3}-\d{3}-\d{4}$"/><br>
<button type="submit" name="submit" onclick="checkphonelength()">submit</button>
</form>
<script type="text/javascript">
function checkphonelength(){
var phNoStringLength = document.getElementById('phNo').value.length;
if(phNoStringLength === 12) {
alert("true");
return true;
}
alert(false);
return false;
}
</script>
</body>
</html>

Related

How to properly control data input?

There is a task to supervise input in . It is necessary to give the ability to enter only strings of numbers ([0-9]) into the entity input. At the same time, if something else is entered, then do not overwrite value and do not display incorrect input in the input. I can't find a solution for my case. Validity check ( target.validity.valid ) didn't work either because I have control over the minimum and maximum lengths. At the same time, I have a universal function for several inputs, but only the entity needs to be checked. Please tell me how to correctly implement the check for input [0-9] and so that nothing else can be entered.
The examples that are on the resource are not suitable because they do not take into account the control of the minimum-maximum length
Below is a shortened code example
const [inputState, setInputState] = useState({title : "", entity: ""})
const handleChangeInputValue = (event) => {
const { target } = event;
const { name, value } = target;
// Need to check for numbers
setInputState({ ...inputState, [name]: value });
};
<input
required
minLength={5}
type="text"
placeholder="Enter name"
name="title"
value={inputState.title}
onChange={handleChangeInputValue}
/>
<input
required
minLength={13}
maxLength={15}
type="text"
placeholder="Enter entity"
name="entity"
value={inputState.entity}
onChange={handleChangeInputValue}
/>
you can use HTML 5
<input type="number" name="someid" />
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>
if(name==='entity' && !value.match(/^\d+$/)) {
return
}

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

javascript alerts refuse to work in form validation?

i keep trying everything to get these alerts to pop up correctly. i started out using nested functions, then threw them out and put it all in one function, and now when I press enter after filling out any one text box it does nothing at all, just puts the strings in the url, instead of alerting like it was before. I'm not sure if its my function call or anything else because I double checked everything and it all seems to check out to me. here is the entire code that doesnt do anything:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- VARIABLE DECLARATION -->
f1.city.focus();
function check_form()
{
at_sign = email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
}
else if(document.f1.state.value.length != 2 || !(state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
}
else if(document.f1.zip.value.length != 5 || document.f1.zip.value.isNaN()==true)
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
}
else if((at_sign<1) || (email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" action="smartform.html">
<b>City</b>
<input type = "text" name = "city" size = "18" value="" onSubmit = "javascript:check_form()">
<b>State</b>
<input type = "text" name = "state" size = "4" value="" onSubmit = "javascript:check_form()">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="" onSubmit = "javascript:check_form()">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="" onSubmit = "javascript:check_form()">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form()">
</form>
</BODY>
</HTML>
edit: nothing seems to be working that everyone says.. here is my new code:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
f1.city.focus();
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
if(f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
return false;
}
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN()==true))
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
return false;
}
else if((at_sign<1) || (f1.email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
return false;
}
else
{
//document.write("Form completed");
}
return false;
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" onSubmit="return check_form(this)">
<b>City</b>
<input type = "text" name = "city" size = "18" value="">
<b>State</b>
<input type = "text" name = "state" size = "4" value="">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="">
<input type = "submit" name = "button" value = "Done" onclick = "return check_form(this)">
</form>
<b>hi</b>
</BODY>
</HTML>
still get no alerts... i put that hi up and got that.. but no alerts......
alright, I know I should probably be using getElementByID, but my new focus is to find out precisely why my code isn't working. Since my lecture outline examples didnt use this method, I want to figure out why the following code doesnt activate alerts like it used to. I simplified it to this:
<!DOCTYPE html>
<html>
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function check_form()
{
document.write("Form started");
var at_sign = document.f1.email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
document.f1.city.focus();
//return false;
}
else if(document.f1.state.value.length != 2 || !(document.f1.state.charCodeAt('0')>=65 && document.f1.state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
document.f1.state.focus();
//return false;
}
else if(document.f1.zip.value.length != 5 || isNaN(document.f1.zip.value)==true)
{
alert('Please enter a 5 digit zip code');
document.f1.zip.focus();
//return false;
}
else if((at_sign<1) || (document.f1.email.value.length<3))
{
alert('Please enter a valid email address');
document.f1.email.focus();
//return false;
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY onLoad= "javascript:document.f1.city.focus();">
<form name = "f1" action="smartform1.html" onSubmit="javascript:check_form();">
<b>City</b>
<input type = "text" name = "city" size = "18">
<b>State</b>
<input type = "text" name = "state" size = "4">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5">
<b>Email</b>
<input type = "text" name = "email" size = "18">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form();">
</form>
</BODY>
</HTML>
I get no errors in console, and now when I type something in, I get the test line "form started" to appear for a split second, along with some mysterious error, and then it all disapears and shows the form. but my question is, why doesnt an alert happen along the way to this result? it seems like even if the page got overwritten, it should still pop up. also, is there a way to pause it with code/and or debugging before it gets to the point where its overwritten? so my basic question is: why don't the alerts pop up, and how do I get the alerts to popup and the focus to remain in the correct field where the function left off within the if/else statement?
update 2: i did a quick screen cap of the errors and it turns out f1.email etc were undefined and indeed causing the thing to not work. So I still want to know how to pause it with code or in the debugger, the posts and links didnt exactly seem to be clear 100% on it. once im in the consonle and in debug mode, where exactly do i go from there to let the program pause on error?
also: if I declare the getElementByID variables at the top of my script in the header, then use them in the function, should that work without all the other event handling methods? I'm attempting this as i type.
You should put the submit listener on the form and pass a reference to the form, and return whatever value the function returns, e.g.
<form onsubmit="return check_form(this);" ...>
You should reference the controls as properties of form using their name, don't use the name as a global variable. And declare all variables.
So the function looks like:
function check_form(form) {
var at_sign = email.search(/#/);
if (form.city.value.length < 1) {
alert('Please enter a city');
f1.city.focus();
// cancel submit by returning false
return false;
} else if (form.state.value.length != 2 || !(form.state.charCodeAt(0) >=65 && state.charCodeAt(0)<=91)) {
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
...
}
You should probably be using a regular expression or lookup for validating the state value rather than charCodeAt.
Using document.write after the page has finished loading (e.g. when submitting the form) will erase the entire content of the page before writing the new content.
Edit
Here's what's wrong with your new code:
<SCRIPT LANGUAGE="JavaScript">
Get rid of the language attribute. It's not harmful (well, in a very specific case it might be).
f1.city.focus();
f1 has no been defined or initialised (see comments above about element names and global variables)
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
f1.email is an input element, it has no search property, you can't call it. It does have a value property that is a string, perhaps you meant:
var at_sign = f1.email.value.search(/#/);
Then there is:
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
again you have forgotten the value property for two of the three expressions, and forgotten to use f1 in the third. You want:
else if(f1.state.value.length != 2 || !(f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=91))
Note that this requires users to enter the state in capital letters, it might help to tell them about that.
Then there is:
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN() == true))
isNaN is a global variable, not a method of strings. If no value has been entered, then the value is the empty string and isNaN('') returns false. If you want to test that 5 digits have been entered then use:
else if (!/^\d{5}$/test(f1.zip.value))
There is no need to test against true, just use it, nor is there a need to group simple expressions:
else if (f1.zip.value.length != 5 || isNaN(f1.zip.value))
Then finally, if all the test pass:
return false;
that stops the form from submitting. You can omit this return statement, returning undefined will let the form submit. Or return true if you really want.
Ok I want to answer your question but first things first lets walk through your
code and clean it up.
Use this as a template of properly formated code:
<!DOCTYPE html>
<html>
<head>
<title>Smart Form</title>
</head>
<body>
<!-- Code goes here -->
<script type="text/javascript">
</script>
</body>
</html>
Tags & attributes don't need to be capitalized. Javascript comments are like this:
/** Comment. */
Html comments are like this:
<!-- Comment. -->
Also nitpick: attributes should be followed by an equal sign not a space. i.e.
<form name="f1" id="smartForm" action="smartform.html"> ... </form>
Next up proper event binding.
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
Next up I'm going to teach you how to fish real quick so you can figure out why this was broken for you and how to fix these bugs in the future. Open up the developer console. Evergreen browsers (Chrome, Firefox etc...) have good ones these day. The trick you should know is how to evaluate your code so that you can see if you did something wrong or not in how you're accessing your data. So look up how to open up the developer console in your browser for your platform and type this into your console:
1+1
Should evaluate to: 2.
Next type: document
If you click around you can see that you can walk through the dom a little bit.
Next load up your smartForm app with my changes above and type:
document.getElementById('smartForm')
You should see your element. This is how to properly query objects in the dom.
You'll notice that if you type document.smartForm doesn't work. You should get null, this should tell you that there should be a way to get the element from the document. Hint, it's getElementById. So if you put id's on all your inputs then you can make a list of all the document objects you can query:
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
Next you can start querying the values and such like you were doing:
cityElement.value.length != 2
A cleaned up version would look like this:
<!DOCTYPE html>
<html>
<head>
<title>Smart form</title>
</head>
<body>
<form id='smartForm' action='smartform.html'>
<b>City</b>
<input type="text" id="city" size="18">
<b>State</b>
<input type="text" id="state" size="4">
<b>Zip Code</b>
<input type="text" id="zip" size="5">
<b>Email</b>
<input type="text" id="email" size="18">
<input type="submit" value="done">
</form>
<script type="text/javascript">
var validateForm = function(evt) {
var error = false;
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
if (cityElement.value.length != 2 ||
!(state.charCodeAt(0) >= 65 && state.charCodeAt(0) <= 91)) {
error = true;
alert('oops');
cityElement.focus();
}
// etc..
if (error) {
evt.preventDefault();
}
};
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
</script>
</body>
</html>
Ok a couple more things I noticed. charCodeAt is for strings only. "hi".chatCodeAt not element.charCodeAt. Also you have this random variable at_sign.
You can save yourself a TON of time and you can learn how to diagnose where the issues are by reading this: https://developer.chrome.com/devtools/docs/console
Learning how to diagnose where the issues are is the single best skill you can learn while trying to get a grapple on javascript. I cannot emphasize this enough, learn how to debug, and you will learn how to program orders of magnitude faster. Trust me, let debugging tutorials be your bread at butter!
Full working example of your code:
http://codepen.io/JAStanton/pen/tjFHn?editors=101
A little less verbose version:
http://codepen.io/JAStanton/pen/iBJAk?editors=101
onSubmit goes in the form, not the inputs, w/o the javascript: Solved =p
<form onsubmit="return check_form();" ...
There are several mishaps in your code that might also cause errors and prevent that from working
Also, check if there are mistakes (like the HTML comment inside script), if an error happens in javascript and is untreated, all javascript in that context stops working. You can check that with any browser debugger (usually F12 will show you a window and display errors if they happen)

JavaScript empty field validation does not work

So, I have a number textbox and I want to validate it using JavaScript. If the user has not input any number, it will prompt him/her to enter one. My codes below:
<input type="number" autofocus id="lol"/>
<input type="button" onClick="validate()" value="Input"/>
<script>
function validate() {
var numfield = document.getElementById("lol").value;
if ( numfield == "") {
document.write("Missing number!");
}
</script>
What is wrong?
You have missed a } at the end of the script. With that fixed, it works normally.
Try to use length property.
if ( numfield.length > 0) {
...
}

Validating phone number with JavaScript

I have a form with three elements. I want to validate the phone number when the user enters it. If the user moves to the next element and phone number contains and characters which is not numbers I want to display an alertbox.
I have written some code but am completely stumped. The problem I am having with my function is, that even if I enter only numbers into the phone number element I still get the alert box displayed. My code looks like this:
<script type="text/javascript">
function validateForm()
{
checkNr= isNaN(document.forms[0].elements[1])
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
}
</script>
<form>
<strong>FULLNAME: </strong><input type="text" / id="name"><br />
<strong>PHONE NR: </strong><input type="text" id="phone" onblur="validateForm()" />
<strong>NATIONALITY</strong><input type="text" id="nat" /><br />
<input type="button" id="subButton" onclick="calc()" value="Submit" />
</form>
Thank you in advance for all your answers and help.
Change
document.forms[0].elements[1]
to
document.forms[0].elements[1].value
You were testing the element itself, not the element's value.
jsFiddle example
BTW, if someone enters a phone number with a dash or parenthesis (e.g. (555) 123-4567) what do you expect to happen?
Here you will find many exemple to achieve your goal :
for example if you can use only number :
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You should do it with a regular expression. See here:
A comprehensive regex for phone number validation
Validate phone number with JavaScript

Categories