简体   繁体   中英

How to programatically set invalid value in input type=number?

I want to set an invalid value to input element with type=number.

I'm writing unit tests for my component which uses input with type=number and it behavior depends on whether the input is empty or not not. Note that I'm treating invalid values like '1.2.3' as not empty, even though it's value property is ''. While it's possible for user in browser to enter invalid values like '1.2.3' I cannot simulate it for my tests.

// let input be HTMLInputElement
input.value = '1.2.3';
console.log(input.value); // ""
console.log(input.validity.valid); // true

I would like to somehow set invalid value for my input type=number, so I could test if my component's logic is valid.

You can use

input.setCustomValidity("dummy value");

to make input.validity.valid return false .

For an idea of why this works, see this CodePen . What it does is it sets an error message that indicates the input is invalid. To make it appear valid once again, use

input.setCustomValidity("");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM