React Js - Unable to enter value in Input Field - javascript

I appreciate all of your idea in advance. My problem here is the input field of the email is not updating. Can anyone give me a solution?
<input
type="text"
placeholder="Enter Email "
onChange={this.emailHandle}
value={this.state.email}
/>
Event handler for the above input field is here:
emailHandle = (e) => {
if (e.target.value !== "undefined") {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (pattern.test(e.target.value)) {
console.log(e.target.value);
this.setState({ email: e.target.value })
}
}
}

The onChange event will never be validate by the regex cause it is called on each key typed. So you start typing andy#gmail.com, with the a but a does not pass the regex... so the state is not updated... so it's like you didn't type a.

What's the initial value of your component state? For one, if you're not initializing the email property on state to be an empty string, and it's undefined, you're blocking that state from ever updating with your undefined check. But you have a bigger problem than that. You're testing to see if the value of the input matches your email regex pattern. That won't ever work if you use that check to block setting state. onChange is going to fire every time the input value changes, and that means it's going to change one character at a time. So what's happening is the user types a character, the onChange fires, but it doesn't match your pattern, and you don't update state.
What you want to do is always update state and then handle this as validation to block submitting the form. Or you could show an error of some kind, but you need to always call setState with the new value on e.target.value.

Related

How to dynamically check if input is empty without using onChange?

I want to get one-time information from the input control when value is empty and when value is not empty
Right now I'm using onChange like below:
<Input onChange={onChangeValue()} />
But this onChangeValue method is running every time when I type into the input, but I want two times information, first when value from input is empty and second when value from input is not empty.
Can someoone tell me what can I do this?
You can put some logic before your onChangeValue() function that checks the input value's length and then calls onChangeValue():
beforeOnChangeValue = function() {
if(arguments[0].target.value.length <= 1) return onChangeValue(arguments)
}
<Input onChange={beforeOnChangeValue} />
This way the onChangeValue() function will only be called when the input is either emptied or when the first character is put in
it seems like you're using controlled components (changing the value of the control on every key typing). I think based on your strategy that you could use a flag in the onChange handler like this
function onChange (evt) {
setIsEmpty(!!evt.target.value);
// Your code ...
}
Then you'll always know if the input is empty or not.
function Form () {
const [isEmpty, setIsEmpty] = React.useState(false);
// onChange here
return <Input className={isEmpty ? 'empty-class' : 'non-empty-class'} />
}

How do I detect whether or not an input with type=time has any values entered

I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.
However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.
In the below example, timeSelector is the input with type="time".
if (timeSelector.value == "") {
timeSelector.classList.add("empty");
} else {
timeSelector.classList.remove("empty");
}
Is there any way to detect this type of thing?
To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.
Well the problem with html5 inputs is they do not give the text in the input if it is not valid. So you can use checkValidity when the user removes focus from the element.
var checkInput = function() {
var value = this.value
var isValid = this.checkValidity()
if (!this.value.length && isValid) {
console.log('empty');
} else if (!this.value.length && !isValid) {
console.log('invalid time entered')
} else {
console.log('valid time entered')
}
}
var input = document.querySelector("input")
input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)
<input type="time" />
Per the specification on Input Elements with type time ( HTML Spec ) :
The value attribute, if specified and not empty, must have a value that is a valid time string.
If the value of the element is not a valid time string, then set it to the empty string instead.
This means that input and change events don't occur until the entire time field has been filled out. Why? Because nothing really has changed.
You may think that you can circumvent this by using keydown or keyup events, but this is simply not the case.
The value is not changed and is therefore inaccessible until a full string that is capable of being parsed as a time is inside the time input box.
By filling in the below example you can see how the events fire. Notice the lack of value until everything is filled in.
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("keydown");
on("keyup");
on("change");
on("input");
<input type="time">
The only way to possibly get around the lack of a changing value is to set a default value as below:
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("change");
<input type="time" value="00:00">
However, with a default value there is a risk that the user will submit a time that isn't something that you'd likely want.
You could write some validation code to take care of this depending on the complexity of your functionality this may be possible.
Overall if this is something you need and the functionality is a bit more complicated than you think you can handle validating yourself, it would be best to either create your own time input interface from other input types, or to use a library or UI kit from a source that has already done the legwork.

How to capture previous value of optionset field onchange?

I have an optionset field in an entity, I want to fire a JavaScript method on this field change. I want to capture the old value of the field on the change. I've got a solution which gets the old value on form load, but this doesn't work on multiple changes.
This has to be solved by our own code implementation. Store the attribute value on form load in a variable, keep the new value in that variable on every change, so you can use that in onChange handler. At the end of business validation inside handler put that new value in variable if success or revert to old value if failed.
var previousValue;
function onFormLoad(){
previousValue = formContext.getAttribute("fieldname").getValue();
}
function onFieldChange(){
if(myBusinessValidationSucceeds){
previousValue = formContext.getAttribute("fieldname").getValue();
}
}
Idea 1 and Idea 2

How To Check For Empty Fields In HTML Form With JavaScript

I'm checking a website registration form with JavaScript code and onchange listeners.
Empty fields/spaces need to be checked for first before checking for illegal characters, too long strings, etc.
I've read this.
But for a null string,
if (field.value ==="")
alert("Empty field!");
this will not generate the desired alert.
People at the end of the above thread suggested that recent browser versions might not accept such a statement.
So, how do I sort out empty/blank/ignored fields ?
EDIT 1
I've already tried
if (!field.value)
but it only provides an alert if the user has already typed some characters in the field and immediately deleted them before entering a blank field. It will not provide an alert just by clicking the mouse on it and then tabbing on to the next field. It looks like I may need to assign a null value to these form fields at the outset . . I am using implicit adding of the changeEvent listener, i.e. on seeing a value explicitly assigned to the onchange attribute of an element, it is activated without any addEventListener(..) statement.
Also,
if (field.value.length == 0)
does not seem to produce any alert.
EDIT 2
Sorted, I think.
I was using the JavaScript null field check as part of a field-by-field validation check on a web form.
I was using onchange as the event handler. This was wrong. What was needed here was onblur since in the case of a completely null field (i.e. a field on which nothing had been entered before tabbing away from it), no change has been effected -- and therefore no onchange event occurs that would trigger a JavaScript alert.
Thanks for your efforts.
I was stuck on this one across a couple of weeks and only sorted it with the help of some experimental programming by a more experienced guy at work here.
In this script you can see an alert of your variable value ( a console.log would be lees noisy :)
The use of === is for type check but in your example does not make sense as you are using an empty string
<script>
var field= {};
checkEquality(field);
field.value = "";
checkEquality(field);
function checkEquality(object){
alert(object.value);
if (object.value === "")
{
alert("===");
}
if(object.value == ""){
alert("==");
}
}
You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null, blank, undefined, zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

Validate input field and restore last valid value

I am trying to set validation on an input field using AngularJS directive, so that when the user types invalid value, the underlying model value changes to the last valid one. This is the contents of the directive:
// returns true/false
function validateValue(value) {
}
ngModelCtrl.$parsers.push(validateValue);
ngModelCtrl.$formatters.push(validateValue);
scope.$watch(attrs.checkValidName, function() {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
So from my understanding, this code will basically run validateValue callback on every change of the input value and mark the input field with valid/invalid depending of the return value. This works great for basic validation, but the side effect of this in case the value is invalid, model value won't contain anything. I'm not sure how to change the code, so that when the value is invalid, the modal value actually contains the last valid value ?
Maybe you can overwrite $$writeModelToScope in the NgModelController. Only update the scope value if the controller is valid.
ngModelCtrl.$$$writeModelToScope = ngModelCtrl.$$writeModelToScope;
ngModelCtrl.$$writeModelToScope = function() {
if (ngModelCtrl.$valid) {
ngModelCtrl.$$$writeModelToScope();
}
};

Categories

Resources