focus a form field on which the function has run (newbie) - javascript

I am trying to focus a form-field after running a validation-function on a form-field which is triggered "onblur" event of that field. What I'm trying to do is get the focus back on that field if it is not valid but it doesn't seem to do it. I've looked for answers on the web but unable to find a solution.
HTML:
<input type="text" id="name" name="name" value="" onblur="validateName();"/>
JavaScript:
function validateName() {
var name = document.getElementById("name");
if (name.value==""||!isNaN(name.value)){
alert("Please enter a valid name. You have left the field blank or entered a number.");
document.getElementById("name").focus();
}
};//END validateName
document.getElementById("name").focus(); is not working as expected.

The code works for me, but to make it a bit more "clean", I did some changes for you:
HTML:
You can "pass" the element with the function call (this), that way, we don't have to look for it anymore in the function itself.
<input type="text" id="name" name="name" value="" onblur="validateName(this)"/>
JavaScript:
The element that is blurred, is passed and stored in element, we call the "focus()" function directly on that.
function validateName(element) {
if (element.value==""||!isNaN(element.value)){
alert("Please enter a valid name. You have left the field blank or entered a number.");
element.focus();
}
};//END validateName

Related

Check textbox on specific format

I have an issue.. I want to check a textbox for a specific format.
I will explain it with an example:
When the user types someting in a textbox. For example a phone number such as: 06-12345678
If the user types the phone number correct, a popup comes up with a message such as: You've entered the phone number correctly.
If the user types it incorrectly, a popup comes up with a message such as: You've entered the phone number incorrectly.
I've already made a jsfiddle for the textboxes, but not for the phone number check.
<input type="text" id="correct" value="06-12345678"><br><br>
<input type="text" id="wrong" value="06 12345678">
Jsfiddle link: Jsfiddle
I hope you can help me out
You use the change event.
function checkNumber(box) {
if (box.value.match("^[0-9]{2}\-[0-9]{8}$") !== null) {
alert("You entered the phone number correctly");
}
else {
alert("You entered the phone number incorrectly");
}
}
<input type="text" onchange="checkNumber(this)" value="" placeholder="Phone Number" />
You can use the pattern attribute in HTML 5.
Example:
<input type="text" pattern="^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$">

Input validation on bootstrap html form with javascript addevent listener

i'm having difficulties with validating the value of a text box element in the html with the addeventlistener in my javascript. It does not properly validate my input in the following ways :
1)Showing "field is empty" even when I have values in that textbox.
2)Only validates when i click submit. <-- (how do i perform the validation as the user clicks out of the text box? )
The following is the relevant html code (with bootstrap classes):
<div class ="col-lg-8">
<div class="form-group">
<label for="inputfirstName" class="col-sm-2 control-label">First Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputfirstName"
placeholder="Enter First Name" />
</div>
</div>
The following is the relevant javascript code to valdiate that the First name text box field is not empty and if it is it should return a custom validation error
window.addEventListener('load',init);
function init()
{
var firstname = document.getElementById("inputfirstName");
firstname.addEventListener('onmouseclick',validateFirstname(firstname));
}
function validateFirstname(e){
var checker = e.value;
if (checker == ""){
e.setCustomValidity("This field must not be blank !");
}
}
I am not really sure, when you want to validate your input.
Currently, you are listening to the user clicking into your textbox and performing the validation in that very moment.
However, since you are only adding the validation error with your call to e.setCustomValidity it won't display until you post your form. This is by design of setCustomValidity. This is explained in more details here: How to force a html5 form validation without submitting it via jQuery
To validate your textbox after the user entered his text, you would use the input and change events. Input fires when the user types something into your textbox, change after the user leaves the textbox. To trigger the validation regardless of the user ever focusing on that field, you also have to set your input to "required". Then to display your message instead of the standard required message of HTML5 you also have to add the invalid event to your event listeners. You can find a more refined answer here with the complete code on how to accomplish this here: Set custom HTML5 required field validation message
<input type="text" class="form-control" id="inputfirstName"
placeholder="Enter First Name" required="required"/>
window.addEventListener('load',init);
function init()
{
var firstname = document.getElementById("inputfirstName");
firstname.addEventListener('input',validateFirstname(firstname));
firstname.addEventListener('change',validateFirstname(firstname));+
}
function validateFirstname(e){
var checker = e.value;
if (checker == ""){
e.setCustomValidity("This field must not be blank !");
}
else{
e.setCustomValidity("");
}
}

Custom HTML5 form validation not showing custom error initially

Basic HTML5 form with custom validation. If the submitted value is not a number, the browser should display the error message "Field must be an number." If you enter "abc" and press submit (or hit enter) the field is marked as invalid, but the error message does not appear. Press submit again (or hit enter) and it will show the message. This double-submit behavior appears on latest versions of Firefox, Chrome, Safari, and IE on Windows and OS X. You will notice that the default "this field is required..." message appears upon the first submission and does not exhibit the odd behavior.
http://jsfiddle.net/6gsr3r4b/
As an aside, I am well aware that this validation will not work in older versions of IE and that the input field could have a type of number that would automatically complete this validation; this is simplified example of my problem for demonstration purposes only.
Javscript
var form = document.getElementById("form");
var field = document.getElementById("field");
form.onsubmit = validateForm;
function validateForm() {
if(isNaN(field.value)) {
field.setCustomValidity("Field must be a number.");
} else {
return true;
}
return false;
}
HTML
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" required>
<input type="submit">
</form>
After setting the validity message, you need to call element.reportValidity() to make it show up.
setCustomValidity(message)
Sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. To clear this state, invoke the function with an empty string passed as its argument. In this case the custom error message is cleared, the element is considered valid, and no message is shown.
reportValidity()
Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns true.
You also need to use event.preventDefault() on the form submission event whenever the input is invalid, so that the form submission doesn't go through.
Here is an example:
var form = document.getElementById('form');
var field = document.getElementById('field');
form.onsubmit = validateForm;
/* this is the function that actually marks the field as valid or invalid */
function validateForm(event) {
if (isNaN(field.value)) {
field.setCustomValidity('Field must be a number.');
field.reportValidity();
event.preventDefault();
}
field.setCustomValidity('');
}
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" required />
<input type="submit" />
</form>
You can also use the HTML5 pattern attribute to do most form validation without JavaScript, or augmented with JavaScript to set custom error messages.
Pattern: A regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.
<form id="form">
<label for="field">Favorite number</label>
<input type="text" id="field" pattern="\d*" title="Field must be a number." required />
<input type="submit" />
</form>

Change input value with Javascript

The title seems easy, but I need help.
I have a form with a field input "email" of which value is null until the user fills it up. Okay, on click of the submit button, I call the function validate() which is:
function validate(){
var email=document.getElementById("email");
if(!(/[\w-\.]{3,15}#([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/.test(email))) {
email.setAttribute('value','Insert a correct email');
email.style.border="2px solid red";
} else {
alert("Valid field"); // This is to test it works
email.style.border="2px solid #63ce40";
this.form.submit();
}
}
What I want to do here is that if the email inserted does not meet the requirements (is not valid), change the value of the input with "Insert a correct email".
If the field is empty and I click submit, it works perfectly, but if I insert text and click submit, the only change will be the field getting a 2px red border, but no text change.
I would like to know what I have to do so that when I click submit the wrong email that was written, is removed and replaced by the text "Insert a correct email".
The input is:
<li>
<input type="text" id="email" name="email"
value="" onfocus="this.value=''" size="40"/>
</li>
And the submit button I'm using:
<input id="bsubmit" type="button" value="Submit"
name="submit" onclick=";this.disabled=true;validate();
this.disabled=false;"/>
Thank you.
It's good that you were trying to use setAttribute at all because it's an important method, but the problem is that you don't want to modify the value attribute in this case, which is a part of the DOM, but you want to modify the <input> element's value property.
email.value = 'Insert a correct email';
http://jsfiddle.net/XJZwm/
Try this email.value = 'Insert a correct email'; instead of email.setAttribute('value','Insert a correct email');

Check if the name field in a form contains a number using javascript and the onchange event

im the definition of a rookie and i hav no idea what im doing. i have to create a function using javascript to perform a validation on the 'name' field in a form. The check will see if there is anything entered or if the name contains a number. On top of this i have to use a onchange event. I tried searching and i got answers put i saw the answers had jquery code in it and i cant use it in this question. Im clueless on what to do, can someone please help? Here is the form im working with
<form method="get">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" onChange="" >
<br>
<label for="age">Age</label>
<input type="age" id="age" placeholder="Age">
<br>
<label for="location">Location</label>
<input type="location" id="location" placeholder="Location">
<br>
<button type="submit">Submit</button>
</form>
Here is a javascript function that takes an input parameter. It will check if the input value has any digit characters in it using regular expression. If it does it sends an alert and then removes all the digit characters (again using regular expression). It will then check if the input value is an empty string and send an alert if it is.
function checkName(input) {
// Check if input contains a digit
if (/\d/.test(input.value)) {
alert('Name contains a number');
// Remove all digit characters
input.value = input.value.replace(/\d/gi, '');
}
// Check if input is empty
if (input.value === '') {
alert('Name is empty');
}
return true;
}​
Add your function call to the onChange property of the input, passing in this object for the function's variable reference:
<input type="text" id="name" placeholder="Name" onChange="checkName(this)" >
Here is a demo showing this working:
http://jsfiddle.net/PMKsS/1/
Something to note. This function will only call when the name input value is changed, as that is what the onChange call will do. Therefore the name input will not be checked for being empty when the form submits.
Also, this is worth a read: Why is using onClick() in HTML a bad practice?. It explains about adding javascript event listeners through javascript rather than through an attribute and why doing the other way isn't great. Although it doesn't offer a way to do this in pure javascript.

Categories

Resources