LoginSignup
1
1

More than 3 years have passed since last update.

ServiceNow - onChangeチェックの落とし穴

Posted at

概要

ServiceNowではフィールドに入力された内容をonChangeスクリプトでチェックすることができる。しかし、それには落とし穴がある。不正な値が入力されていてもフォームを申請することができる。
間違えた内容の申請を防止するにはonSubmitのスクリプトでも同じチェックをすることもできるが、正規表現を定義した方が簡単にできる。

onChangeチェックの例

次のスクリプトはフィールド「phone_number」の形式をチェックしている。正しくない場合はメッセージを表示する。

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    try {
        var phone = newValue.replace(/\s/g, '');
        phone = phone.substring(0, 10);
        phone = phone.substr(0, 4) + ' ' + phone.substr(4, 3) + ' ' + phone.substr(7, 3);

        //var reg = new RegExp("^0[45][0-9]{2} [0-9]{3} [0-9]{3}$");
        var reg = /^0[45][0-9]{2} [0-9]{3} [0-9]{3}$/;
        if (reg.test(phone)) {
            if (newValue != phone) {
                g_form.setValue('phone_number', phone);
            }
        } else {
            g_form.setValue('phone_number', '');
            g_form.showFieldMsg('phone_number', 'Phone number should start with 0 and be 10 digits', "error");
        }

    } catch (e) {
        alert(e.message);
    }
}

実行例
image.png

しかし「Order Now」ボタンを押下すると間違えた内容で注文されてしまう。
image.png

正規表現

正規表現の定義

image.png

フィールドでの指定

image.png

実行

フィールドを入力した後にエラーメッセージが表示される。
image.png

「Order Now」ボタンを押下するとフォームにエラーメッセージが表示されて申請はされない。
image.png

以上

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1