Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm Working on a small project using jQuery and I'm doing form validation, I would like to know if is there any solution to avoid repeaters in my code, talking about (addClass and removeClass)

my code :

if (value.string.match(regex)) {
   $('#' + index).removeClass('is-invalid')
   $('#' + index).addClass('is-valid')
} else {
   $('#' + index).removeClass('is-valid')
   $('#' + index).addClass('is-invalid')
}
question from:https://stackoverflow.com/questions/66055800/is-there-any-way-toggleclass-without-rewriting-the-same-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
131 views
Welcome To Ask or Share your Answers For Others

1 Answer

Instead of having both a is-invalid class and a is-valid class, change your CSS to have just one class, that gets toggled when validation changes. For example, instead of

.some-input.is-valid {
  // rules
}
.some-input.is-invalid {
  // more rules
}

use

.some-input {
  // rules
}
.some-input.invalid {
  // more rules WHICH OVERRIDE the original rules if needed
}

Then all you need is:

const match = Boolean(value.string.match(regex));
$('#' + index).toggleClass('invalid', match);

Just like with classList.toggle, you can pass a second argument to jQuery's toggleClass to indicate whether the class should exist or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...